<template>
  <div
    class="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center p-4"
  >
    <div class="w-full max-w-md">
      <!-- Logo/标题区域 -->
      <div class="text-center mb-8">
        <div
          class="mx-auto w-16 h-16 bg-gradient-to-br from-blue-500 to-purple-600 rounded-2xl flex items-center justify-center mb-4 shadow-lg"
        >
          <Icon name="robot" size="32" class="text-white" />
        </div>
        <h1 class="text-3xl font-bold text-gray-900 mb-2">AI 对话助手</h1>
        <p class="text-gray-600">欢迎回来，请登录您的账户</p>
      </div>

      <!-- 登录表单卡片 -->
      <div class="bg-white rounded-2xl shadow-xl border border-gray-100 p-8">
        <!-- 切换按钮 -->
        <div class="flex mb-6 bg-gray-100 rounded-lg p-1">
          <button
            @click="toggleLoginType"
            :class="[
              'flex-1 py-2 px-4 rounded-md text-sm font-medium transition-all duration-200',
              !isAdminLogin
                ? 'bg-white text-gray-900 shadow-sm'
                : 'text-gray-600 hover:text-gray-900',
            ]"
          >
            用户登录
          </button>
          <button
            @click="toggleLoginType"
            :class="[
              'flex-1 py-2 px-4 rounded-md text-sm font-medium transition-all duration-200',
              isAdminLogin
                ? 'bg-white text-gray-900 shadow-sm'
                : 'text-gray-600 hover:text-gray-900',
            ]"
          >
            管理员登录
          </button>
        </div>

        <h2 class="text-xl font-semibold text-gray-900 mb-6 text-center">
          {{ isAdminLogin ? '管理员登录' : '用户登录' }}
        </h2>

        <form @submit.prevent="handleLogin" class="space-y-6">
          <!-- 用户名输入 -->
          <div class="form-group">
            <label class="form-label">用户名</label>
            <input
              v-model="loginForm.username"
              type="text"
              placeholder="请输入用户名"
              class="input"
              :class="{ 'input-error': errors.username }"
              @blur="validateField('username')"
            />
            <span v-if="errors.username" class="form-error">{{ errors.username }}</span>
          </div>

          <!-- 密码输入 -->
          <div class="form-group">
            <label class="form-label">密码</label>
            <div class="relative">
              <input
                v-model="loginForm.password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码"
                class="input pr-12"
                :class="{ 'input-error': errors.password }"
                @blur="validateField('password')"
                @keyup.enter="handleLogin"
              />
              <button
                type="button"
                @click="showPassword = !showPassword"
                class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 transition-colors"
              >
                <Icon :name="showPassword ? 'eye-off' : 'eye'" size="20" />
              </button>
            </div>
            <span v-if="errors.password" class="form-error">{{ errors.password }}</span>
          </div>

          <!-- 登录按钮 -->
          <button
            type="submit"
            :disabled="loading || !isFormValid"
            class="btn-primary w-full py-3 text-base font-medium disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <div v-if="loading" class="flex items-center justify-center">
              <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
              登录中...
            </div>
            <span v-else>登录</span>
          </button>
        </form>

        <!-- 底部链接 -->
        <div class="mt-6 pt-6 border-t border-gray-200">
          <div class="flex justify-between items-center">
            <button
              v-if="!isAdminLogin"
              @click="$router.push('/register')"
              class="btn-text text-sm"
            >
              注册新账户
            </button>
            <div v-else class="flex-1"></div>

            <button @click="toggleLoginType" class="btn-text text-sm">
              {{ isAdminLogin ? '切换到用户登录' : '切换到管理员登录' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 底部信息 -->
      <div class="text-center mt-8 text-sm text-gray-500">
        <p>© 2024 AI 对话助手. 保留所有权利.</p>
      </div>
    </div>
  </div>
</template>

<script>
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Icon from '../components/icons/Icon.vue'

export default {
  name: 'Login',
  components: {
    Icon,
  },
  setup() {
    const store = useStore()
    const router = useRouter()

    const loading = ref(false)
    const isAdminLogin = ref(false)
    const showPassword = ref(false)

    const loginForm = reactive({
      username: '',
      password: '',
    })

    const errors = reactive({
      username: '',
      password: '',
    })

    const rules = {
      username: [{ required: true, message: '请输入用户名' }],
      password: [{ required: true, message: '请输入密码' }],
    }

    const isFormValid = computed(() => {
      return (
        loginForm.username.trim() &&
        loginForm.password.trim() &&
        !errors.username &&
        !errors.password
      )
    })

    const validateField = (field) => {
      const value = loginForm[field]
      const fieldRules = rules[field]

      for (const rule of fieldRules) {
        if (rule.required && !value.trim()) {
          errors[field] = rule.message
          return false
        }
      }

      errors[field] = ''
      return true
    }

    const validateForm = () => {
      let isValid = true
      Object.keys(rules).forEach((field) => {
        if (!validateField(field)) {
          isValid = false
        }
      })
      return isValid
    }

    const handleLogin = async () => {
      if (!validateForm()) return

      try {
        loading.value = true

        if (isAdminLogin.value) {
          await store.dispatch('adminLogin', loginForm)
          showSuccessMessage('管理员登录成功')
          router.push('/admin')
        } else {
          await store.dispatch('login', loginForm)
          showSuccessMessage('用户登录成功')
          router.push('/chat')
        }
      } catch (error) {
        console.error('Login error:', error)
        showErrorMessage(error.message || '登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }

    const toggleLoginType = () => {
      isAdminLogin.value = !isAdminLogin.value
      loginForm.username = ''
      loginForm.password = ''
      errors.username = ''
      errors.password = ''
    }

    const showSuccessMessage = (message) => {
      if (window.$toast) {
        window.$toast.success(message)
      }
    }

    const showErrorMessage = (message) => {
      if (window.$toast) {
        window.$toast.error(message)
      }
    }

    return {
      loading,
      isAdminLogin,
      showPassword,
      loginForm,
      errors,
      isFormValid,
      validateField,
      handleLogin,
      toggleLoginType,
    }
  },
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-form {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.login-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.form-links {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
</style>
